// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as path from 'path';
const utils = require("./utils");
const { transpile } = require("./transpiler");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "goldenpy" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('goldenpy.helloWorld', () => {
		// The code you place here will be executed every time your command is executed

		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from goldenpy!');
	});

	context.subscriptions.push(disposable);

	function fileType (filename:string) {
		let index1 = filename.lastIndexOf(".");
		let index2 = filename.length;
		let tp = filename.substring(index1, index2);
		if (".py" === tp) {
			tp = filename.substring(index1-2, index2);
			return tp;
		}
		return tp;
	};

	const didSaveEvent = vscode.workspace.onDidSaveTextDocument((document) => {
		// console.log(document.fileName);
		const fileSuffix = fileType(document.fileName);
		// console.log(fileSuffix);
		if (".z.py" === fileSuffix) {
			let zfilePath = path.dirname(document.fileName);
			let baseFilenameDotZ = path.parse(document.fileName).name;
			let baseFilename = baseFilenameDotZ.substring(0, baseFilenameDotZ.lastIndexOf("."));
			let zFileContent = document.getText();
			const pyFile = path.join(zfilePath, baseFilename + ".py");
			let pyFileContent;
			try {						
				pyFileContent = transpile(zFileContent, document.fileName, zfilePath);
			} catch (error) {
				console.log(error);
			}
			// console.log(pyFileContent);
			utils.writeFileContents(pyFile, pyFileContent);		
		}
	});

	context.subscriptions.push(didSaveEvent);
}

// this method is called when your extension is deactivated
export function deactivate() {}
